﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Shopfloormanagement;
using LSQL;
using System.Globalization;

namespace Shopfloormanagment.Forms
{
    public partial class attendance_input : Form
    {
        public static attendance_input instance = new attendance_input();
        public static attendance_input frm = new attendance_input();
        public attendance_input()
        {
            instance = this;
            InitializeComponent();
        }

        private void Initial_cmb(Control control)
        {
            if (control is UIComboBox comboBox)
            {
                //comboBox.Items.Clear();
                comboBox.Font = new Font("Arial", 9);
                //comboBox.Items.Add("Attend");
                //comboBox.Items.Add("Not Attendings");
                comboBox.SelectedItem = "Attend";
                //comboBox.Click += ComboBox_Click;

            }
            else
            {
                var controlCollection = control.Controls;
                foreach (Control subControl in controlCollection)
                {
                    Initial_cmb(subControl);
                }
            }
        }


        private void ComboBox_Click(object sender, EventArgs e)
        {
            if (sender is UIComboBox comboBox)
            {
                // 输出被点击的ComboBox的Name到控制台
                Console.WriteLine($"Clicked ComboBox Name: {comboBox.Name}");
            }
        }

        string[] members = null;
        int[] membersID = null;
        bool[] comboBoxBooleanValues;

        private void LoadMember()
        {
            DataTable dtMem = SQL.ReturnDataTable3(SystemInfo.SQL, "Meeting", $"MeetingLevel = {SystemInfo.readLevel} and MeetingDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");
            if (dtMem.Rows.Count <= 0)
            {
                return;
            }
            DataTable member = SQL.ReturnDataTable3(SystemInfo.SQL, "Employees", $"ID in ({dtMem.Rows[0]["MeetingMember"]})");
            //DataTable member = SQL.ReturnDataTable3(SystemInfo.SQL, "View_MeetingAttendance", $"MeetingID = {DevMainForm.MeetingId} and Year = {DateTime.Now.Year} and Week = {GetWeek(DateTime.Now)}");
            int comboBoxCount = member.Rows.Count;
            members = new string[member.Rows.Count];
            membersID = new int[member.Rows.Count];
            comboBoxBooleanValues = new bool[comboBoxCount]; // 初始化布尔数组大小

            for (int i = 0; i < comboBoxCount; i++)
            {
                // 动态添加Label
                Label label = new Label();
                label.Text = member.Rows[i]["FullName"].ToString();
                label.Parent = panel1;
                label.Name = member.Rows[i]["FullName"].ToString();
                label.Location = new System.Drawing.Point(7, 12 + i * 38);
                label.AutoSize = true;
                label.Font = new Font("Arial", 9);
                panel1.Controls.Add(label);
                members[i] = label.Text;
                membersID[i] = (int)member.Rows[i]["ID"];

                // 动态添加UIComboBox
                UIComboBox cmb = new UIComboBox();
                cmb.Parent = panel1;
                cmb.Items.Add("Not Attend");     // 表示 false
                cmb.Items.Add("Attend"); // 表示 true
                cmb.Name = $"cb{i}";
                cmb.Location = new System.Drawing.Point(18, 5 + i * 38);
                cmb.SelectedIndexChanged += (sender, e) => ComboBox_SelectedIndexChanged(sender, e); // 传入索引i

                // 添加到Panel和设置初始值
                panel2.Controls.Add(cmb);

                comboBoxBooleanValues[i] = true; // 初始值为 true/false
            }



        }


        // ComboBox SelectedIndexChanged事件处理方法
        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sender is UIComboBox cmb)
            {
                int controlIndex = cmb.Parent.Controls.IndexOf(cmb);
                // 更新数组中的布尔值
                bool res;
                if (cmb.SelectedItem.ToString() == "Attend")
                {
                    res = true;
                }
                else
                {
                    res = false;
                }
                comboBoxBooleanValues[controlIndex] = res; // true表示"Attend"，false表示"Not Attend"
                //Console.WriteLine($"{cmb.Name} SelectedValue as bool: {comboBoxBooleanValues[index]}");
            }
        }

        // 获取所有ComboBox的布尔值
        public bool[] GetComboBoxBooleanValues()
        {
            return (bool[])comboBoxBooleanValues.Clone(); // 返回布尔数组的副本
        }

        private void attendance_input_Load(object sender, EventArgs e)
        {
            frm = this;
            for (int i = panel1.Controls.Count - 1; i >= 0; i--)
            {
                Control control = panel1.Controls[i];

                // 如果控件不是 Panel 类型，则移除
                if (!(control is Panel))
                {
                    panel1.Controls.Remove(control);
                }
            }
            panel2.Controls.Clear();
            LoadMember();
            //cb默认选择第一个
            Initial_cmb(this);
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public int GetWeek(DateTime currentDate)
        {
            // 获取当前文化信息
            CultureInfo cultureInfo = CultureInfo.CurrentCulture;

            // 获取 Calendar 对象
            Calendar calendar = cultureInfo.Calendar;

            // 指定周的第一天是星期几，通常是星期一或星期天
            CalendarWeekRule weekRule = cultureInfo.DateTimeFormat.CalendarWeekRule;

            // 获取当前日期在一年中的周数
            int weekNumber = calendar.GetWeekOfYear(currentDate, weekRule, DayOfWeek.Monday);

            return weekNumber;
        }
        private void uiButton2_Click(object sender, EventArgs e)
        {
            int isUpdated = 0;
            //写入签到信息
            //获得今天日期
            DateTime now = DateTime.Now;
            string year = now.Year.ToString();
            int weekNum = GetWeek(now);
            DayOfWeek today = DateTime.Now.DayOfWeek;

            //判断是否有数据,如果没有写入，如果有update
            for (int i = 0; i < membersID.Length; i++)
            {
                DataTable res = LSQL.SQL.ReturnDataTable2(SystemInfo.SQL, "MeetingAttendance", $"MemberID = '{membersID[i]}' and MeetingID = {DevMainForm.MeetingId} and Year = {year} and Week = {weekNum}");

                if (res.Rows.Count > 0)
                {
                    int id = (int)res.Rows[0]["ID"];
                    bool update = LSQL.SQL.Update(SystemInfo.SQL, "MeetingAttendance", $"{today} = '{Convert.ToInt32(comboBoxBooleanValues[i])}'", $"ID = {id}");
                    if (update)
                    {
                        isUpdated += 1;
                    }
                }
                else
                {
                    string columns = $"MeetingID,MemberID,Year,Week,{today},Sort";
                    string values = $"{DevMainForm.MeetingId},'{membersID[i]}',{year},{weekNum},'{Convert.ToInt32(comboBoxBooleanValues[i])}',{i+1}";
                    int result = LSQL.SQL.Insert(SystemInfo.SQL, "MeetingAttendance", columns, values);
                    if (result > 0)
                    {
                        isUpdated += result;
                    }
                }
            }

            if (SystemInfo.readLevel == 4)
            {
                //判断是否有数据,如果没有写入，如果有update
                for (int i = 0; i < members.Length; i++)
                {
                    DataTable res = LSQL.SQL.ReturnDataTable2(SystemInfo.SQL, "MeetingAttendance", $"EmployeeName = '{members[i]}' and MeetingLevel = 4 and Year = {year} and Week = {weekNum}");

                    if (res.Rows.Count > 0)
                    {
                        int id = (int)res.Rows[0]["ID"];
                        bool update = LSQL.SQL.Update(SystemInfo.SQL, "MeetingAttendance", $"{today} = '{comboBoxBooleanValues[i]}'", $"ID = {id}");
                        if (update)
                        {
                            isUpdated += 1;
                        }
                    }
                    else
                    {
                        string columns = $"MeetingLevel,DepartmentID,EmployeeName,Year,Week,FactoryID,{today}";
                        string values = $"4,0,'{members[i]}',{year},{weekNum},{SystemInfo.readFactory},'{comboBoxBooleanValues[i]}'";
                        int result = LSQL.SQL.Insert(SystemInfo.SQL, "MeetingAttendance", columns, values);
                        if (result > 0)
                        {
                            isUpdated += result;
                        }
                    }
                }

            }
            else
            {
                for (int i = 0; i < members.Length; i++)
                {
                    DataTable res = LSQL.SQL.ReturnDataTable2(SystemInfo.SQL, "MeetingAttendance", $"EmployeeName = '{members[i]}' and MeetingLevel != 4 and FactoryID = {SystemInfo.readFactory} and Year = {year} and Week = {weekNum} and DepartmentID = {SystemInfo.readparentDep}");
                    if (res.Rows.Count > 0)
                    {
                        int id = (int)res.Rows[0]["ID"];
                        bool update = LSQL.SQL.Update(SystemInfo.SQL, "MeetingAttendance", $"{today} = '{comboBoxBooleanValues[i]}'", $"ID = {id}");
                        if (update)
                        {
                            isUpdated += 1;
                        }
                    }
                    else
                    {
                        string columns = $"MeetingLevel,DepartmentID,EmployeeName,Year,Week,FactoryID,{today}";
                        string values = $"{SystemInfo.readLevel},{SystemInfo.readparentDep},'{members[i]}',{year},{weekNum},{SystemInfo.readFactory},'{comboBoxBooleanValues[i]}'";
                        int result = LSQL.SQL.Insert(SystemInfo.SQL, "MeetingAttendance", columns, values);
                        if (result > 0)
                        {
                            isUpdated += result;
                        }
                    }
                }

            }
            
            MessageBox.Show($"更新{isUpdated}人的签到信息", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            DevMainForm.instance.LoadMeeting();
            this.Close();
        }
    }
}
